#include "iocontroller.h"

IOController::IOController()
{
	jopened = false;
	j1opened = false;
	j2opened = false;
	keystate = NULL;
	joystick = NULL;
	joystick1 = NULL;
	joystick2 = NULL;
}


bool IOController::openJoystick(int num_joystick)
{
	// Initialize the joystick subsystem
	SDL_InitSubSystem(SDL_INIT_JOYSTICK);

	// Check for joystick
	if(SDL_NumJoysticks() <= num_joystick)
		return false;

	// Open joystick
	joystick = SDL_JoystickOpen(num_joystick);
		if (joystick == NULL) return false;
	return true;
	/*
	if(num_joystick == 1){
		joystick1 = SDL_JoystickOpen(num_joystick);
		if (joystick1 == NULL)
		  return false;
	}
	else if(num_joystick == 2){
		joystick2 = SDL_JoystickOpen(num_joystick);
		if (joystick2 == NULL)
		  return false;
	}
	return true;
	*/
}


JoystickState IOController::getJoystickState(int num_joystick)
{
	JoystickState state;
	memset(&state,0,sizeof(JoystickState));

	if ( joystick == NULL )
	{	
		if (openJoystick(num_joystick)){
			std::cout << "Joystick #" << num_joystick << " opened." << std::endl;
		}
		else{
			return state;
		}
	}

	state.num_axis = SDL_JoystickNumAxes((::SDL_Joystick*) joystick);
	state.num_buttons = SDL_JoystickNumButtons( (::SDL_Joystick*)joystick);

	if (state.num_axis > 8) state.num_axis = 8;
	if (state.num_buttons > 16) state.num_buttons = 16;
	float umbral = 0.15;
	for (int i = 0; i < state.num_axis; ++i){ //axis
		state.axis[i] = SDL_JoystickGetAxis((::SDL_Joystick*) joystick,i) / 32768.0f; //range -32768 to 32768
		if (state.axis[i] < umbral && state.axis[i] > -umbral) state.axis[i] = 0;

	}
	for (int i = 0; i < state.num_buttons; ++i) //buttons
		state.button[i] = SDL_JoystickGetButton((::SDL_Joystick*) joystick,i);
	state.hat = (HATState)(SDL_JoystickGetHat((::SDL_Joystick*) joystick,0) - SDL_HAT_CENTERED); //one hat is enough

	return state;
}

/*
Unit8* IOController::getKeyState()
{

}
*/

int IOController::getMouseLast_x()
{
	return mouse_last_x;
}

int IOController::getMouseLast_y()
{
	return mouse_last_y;
}
/*
int IOController::getMouseLast_x()
{
	return mouse_last_x;
}

int IOController::getMouseLast_y()
{
	return mouse_last_y;
}
*/
void IOController::setMouseLast_x(int mouse_x)
{
	mouse_last_x = mouse_x;
}

void IOController::setMouseLast_y(int mouse_y)
{
	mouse_last_y = mouse_y;
}

